package com.baizhi.cmfz.config;



import com.baizhi.cmfz.realm.AuthorRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.mgt.WebSecurityManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;


//  和SpringBoot集成之后  是不需要ini配置文件的
@Configuration
public class ShiroConfig {


    private Logger logger = LoggerFactory.getLogger(ShiroConfig.class);

    //1.创建过滤器
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(WebSecurityManager securityManager){
        logger.info("创建shiro过滤器");
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //设置过滤规则
        HashMap map = new HashMap();
        // anon 代表匿名可访问 就是不用登录就可以访问 不过滤
        // authc 代表登录后才能访问  需要认证  会被过滤
        // 支持通配符*
        // 注意拦截规则 一个一个配置
        map.put("/login.jsp","anon");
        map.put("/login/*","anon");
        map.put("/main/*","authc");
        map.put("/guru/*","authc");
        map.put("/menu/*","authc");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        //设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        return shiroFilterFactoryBean;
    }
    //创建安全管理器
    //@Bean 的方法形参 如果工厂中有对应的类型的对象 Spring会自动赋值

    @Bean
    public WebSecurityManager getWebSecurityManager(AuthorRealm authorRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // 设置自定义realm
        securityManager.setRealm(authorRealm);
        return securityManager;
    }

    //创建自定义的Realm
    @Bean
    public AuthorRealm getAuthorRealm(){

        AuthorRealm authorRealm = new AuthorRealm();

        // 为realm设置凭证匹配器
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        // 设置加密算法
        credentialsMatcher.setHashAlgorithmName("md5");
        // 设置hash次数
        credentialsMatcher.setHashIterations(1024);
        authorRealm.setCredentialsMatcher(credentialsMatcher);

        return authorRealm;
    }
}
